//
//  GHPopMenuView.m
//  12-guhu_weibo
//
//  Created by GHapple on 15-2-1.
//  Copyright (c) 2015年 itcast. All rights reserved.
//

#import "GHPopMenuView.h"

@implementation GHPopMenuView

static UIWindow *_window;
static dismissBlock _dismiss;
static UIViewController *_contentVC;

+ (void)popFrom:(UIView *)fromView content:(UIView *)content dismiss:(dismissBlock)dismiss{
    [self popFrom:fromView.frame inView:fromView.superview content:content dismiss:dismiss];
}

+ (void)popFrom:(CGRect)fromRect inView:(UIView *)inView content:(UIView *)content dismiss:(dismissBlock)dismiss{

    _dismiss =  [dismiss copy];
    // 创建window
    _window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    _window.hidden = NO;
    _window.windowLevel = UIWindowLevelAlert;
    
    
    // 创建蒙版
    
    UIButton *cover = [[UIButton alloc]init];
    cover.frame = [UIScreen mainScreen].bounds;
    cover.backgroundColor = [UIColor clearColor];
    [cover addTarget:self action:@selector(coverClick:) forControlEvents:UIControlEventTouchUpInside];
    [_window addSubview:cover];
    
    //创建菜单
    UIImageView *menuView = [[UIImageView alloc]init];
    // 开启用户交互
    menuView.userInteractionEnabled = YES;
    UIImage *image = [UIImage imageNamed:@"popover_background"];
    menuView.image = image;
    
    [cover addSubview:menuView];
    // 添加内容到菜单
    content.x = 15;
    content.y = 18;
    [menuView addSubview:content];
    // 设置菜单容器的frame
    
    CGFloat menuViewW = CGRectGetMaxX(content.frame) + content.x;
    CGFloat menuViewH = CGRectGetMaxY(content.frame) + content.y;
    menuView.frame = CGRectMake(0, 0, menuViewW, menuViewH);
    
    // 获取指向控件的frame,并且转化为同模板一个控制器的frame
    CGRect  resultFrame = [_window convertRect:fromRect fromView:inView];
    menuView.y  = CGRectGetMaxY(resultFrame);
    menuView.centerX =  resultFrame.origin.x + (resultFrame.size.width * 0.5);
    


}

+ (void)popFrom:(UIView *)fromView contentVC:(UIViewController *)contentVC dismiss:(dismissBlock)dismiss
{
    // 保命
    _contentVC = contentVC;
    
    // 显示
    [self popFrom:fromView content:_contentVC.view dismiss:dismiss];
}

+ (void)coverClick:(UIButton*)btn{
    
    _window = nil;
    _contentVC = nil;
    if (_dismiss !=nil) {
        _dismiss();
    }
//    GHLog(@"%s",__func__);
}
@end
